//
//  Ch3_1Controller.swift
//  learn-gl-es-swift
//
//  Created by LimitLiu on 2019/9/9.
//  Copyright © 2019 LimitLiu. All rights reserved.
//

import UIKit
import GLKit

struct SceneVertex2_3 {
    var positionCoords: GLKVector3
}

class Ch2_3Controller: GLKViewController {
    
    var baseEffect = GLKBaseEffect()
    var vertexBuffer: GLVertexAttribArrayBuffer!
    
    let vertices: [SceneVertex2_3] = [
        SceneVertex2_3(positionCoords: vec(-0.5, -0.5, 0)),
        SceneVertex2_3(positionCoords: vec(0.5, -0.5, 0)),
        SceneVertex2_3(positionCoords: vec(-0.5, 0.5, 0)),
    ]
    
    deinit {
        let view = self.view as! GLKView
        GLContext.setCurrent(view.context)
        vertexBuffer = nil
        GLContext.setCurrent(nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let view = self.view as! GLKView
        view.context = GLContext(api: .openGLES3)!
        GLContext.setCurrent(view.context)
        baseEffect.useConstantColor = GLboolean(GL_TRUE)
        baseEffect.constantColor = vec(0, 1, 0, 1)
        
        (view.context as! GLContext).clearColor = vec(1, 1, 1, 1)
        vertexBuffer = GLVertexAttribArrayBuffer(
            attribStride: GLsizei(MemoryLayout<SceneVertex2_3>.stride),
            numberOfVertices: GLsizei(vertices.count),
            data: vertices,
            usage: GLenum(GL_STATIC_DRAW)
        )
    }
    
    override func glkView(_ view: GLKView, drawIn rect: CGRect) {
        self.baseEffect.prepareToDraw()
        (view.context as! GLContext).clear(GLbitfield(GL_COLOR_BUFFER_BIT))
        vertexBuffer.prepareToDraw(
            attrib: GLuint(GLKVertexAttrib.position.rawValue),
            numberOfCoordinates: 3,
            attribOffset: GLsizeiptr(0),
            shouldEnable: true
        )
        vertexBuffer.drawArray(
            mode: GLenum(GL_TRIANGLES),
            startVertexIdx: 0,
            numberOfVertices: 3
        )
    }
}
